/* 
 * AUTHOR: Kevin Lam
 */

package com.apps.ubc.cc.ajax;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;


import com.apps.datastore.AccountInformationDatastore;
import com.apps.datastore.dao.WorklistItemObject;
import com.apps.services.FinalExamScheduleService;
import com.apps.ubc.cc.model.FinalScheduleModel;

public class ExamScheduleController extends HttpServlet {
	
	FinalExamScheduleService fs = new FinalExamScheduleService();
	AccountInformationDatastore d = new AccountInformationDatastore();
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) {
		String user = null;
		Cookie[] cookies = req.getCookies();
		StringBuilder builder= new StringBuilder();
		builder.append("<response>\n");
		//String xmlout = "<response>\n";
		for (int i = 0; i < cookies.length; i++) {
			if (cookies[i].getName().equals("user"))
				user = cookies[i].getValue();
		}
		String email = req.getParameter("email");
		if(user.equals(email) || d.checkSubscriptionExists(user, email)) {
			List<WorklistItemObject> wiol = d.getWorklistAsWIO(email);
			List<FinalScheduleModel> fsml = fs.getFinalSchedule(wiol);
			for(Iterator<FinalScheduleModel> i = fsml.iterator(); i.hasNext();){
				FinalScheduleModel fsm = i.next();
				builder.append("\t<item>\n");
				builder.append("\t\t<dept>"+fsm.getDepartment()+"</dept>\n");
				builder.append("\t\t<course>"+fsm.getCourse()+"</course>\n");
				builder.append( "\t\t<section>"+fsm.getSection()+"</section>\n");
				builder.append( "\t\t<building>"+StringEscapeUtils.escapeXml(fsm.getBuilding())+"</building>\n");
				builder.append("\t\t<time>"+fsm.getTime()+"</time>\n");
				builder.append("\t\t<split>"+StringEscapeUtils.escapeXml(fsm.getAlphaSplit())+"</split>\n");
				builder.append("\t</item>\n");
				
//				xmlout += "\t<item>\n";
//				xmlout += "\t\t<dept>"+fsm.getDepartment()+"</dept>\n";
//				xmlout += "\t\t<course>"+fsm.getCourse()+"</course>\n";
//				xmlout += "\t\t<section>"+fsm.getSection()+"</section>\n";
//				xmlout += "\t\t<building>"+StringEscapeUtils.escapeXml(fsm.getBuilding())+"</building>\n";
//				xmlout += "\t\t<time>"+fsm.getTime()+"</time>\n";
//				xmlout += "\t\t<split>"+StringEscapeUtils.escapeXml(fsm.getAlphaSplit())+"</split>\n";
//				xmlout += "\t</item>\n";
			}
		}
		else {
			builder.append("\t<error>Invalid login<error>\n");
			//xmlout += "\t<error>Invalid login<error>\n";
		}
		builder.append("</response>");
		//xmlout += "</response>";
		try {
			resp.setContentType("text/xml");
			resp.getWriter().write(builder.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
